﻿using System.Collections.Generic;
using cmdb.keede.entity;
using cmdb.keede.data;
using System.Linq;
using cmdb.keede.common;
using System.Threading.Tasks;

namespace cmdb.keede.service
{
    public class EnvironmentInfoService : IEnvironmentInfoService
    {
        readonly IEnvironmentInfoRepository _environmentInfoResp;
        readonly IUnitOfWork _unitOfWork;

        public EnvironmentInfoService(IEnvironmentInfoRepository environmentInfoResp, IUnitOfWork unitOfWork)
        {
            _environmentInfoResp = environmentInfoResp;
            _unitOfWork = unitOfWork;
        }

        public async Task<BizResult<List<EnvironmentInfo>>> GetEnvironmentInfosAsync(int pageIndex, int pageSize)
        {
            return await _environmentInfoResp.GetPageAsync(new Pager(pageIndex, pageSize), w => w.Status == EnumEnvironmentStatus.Enabled, o => o.Id, false);
        }

        public async Task<List<EnvironmentInfo>> GetAllEnvironmentInfosAsync()
        {
            return (await _environmentInfoResp.GetManyAsync(w => w.Status == EnumEnvironmentStatus.Enabled)).ToList();
        }

        public async Task<BizResult<EnvironmentInfo>> GetEnvironmentInfoAsync(int id)
        {
            var obj = await _environmentInfoResp.GetByIdAsync(id);
            return new BizResult<EnvironmentInfo>(obj);
        }

        public async Task<BizResult<bool>> DeleteEnvironmentInfoAsync(int id)
        {
            var obj = await _environmentInfoResp.GetByIdAsync(id);
            if (obj != null)
            {
                obj.Status = EnumEnvironmentStatus.Disabled;
            }
            await _unitOfWork.CommitAsync();
            return new BizResult<bool>(true);
        }

        public async Task<BizResult<bool>> AddOrUpdateEnvInfoAsync(EnvironmentInfo env)
        {
            if (env.Id == 0)
                _environmentInfoResp.Add(env);
            else
            {
                var obj = await _environmentInfoResp.GetByIdAsync(env.Id);
                obj.Name = env.Name;
                obj.Description = env.Description;
            }

            await _unitOfWork.CommitAsync();
            return new BizResult<bool>(true);
        }
    }
}
